package com.rzico.sbl.ui.order

import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityDeliverSendBinding
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.other.OrderService
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.serviceId
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.DeliverViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.other.DecimalNumberFilter
import com.xinnuo.common.other.NameLengthFilter
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showBottomPhoneDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONArray
import org.json.JSONObject

class DeliverSendActivity : BaseActivity(R.layout.activity_deliver_send) {

    private val mBinding by lazy { ActivityDeliverSendBinding.bind(getRootView()) }

    private var mSendMode = ""     //操作类型：派单(unconfirmed)、转派(shipped)
    private var mSellerId = ""     //销售店主ID
    private var mShopOwnerId = ""  //配送店主ID
    private var mShopId = ""       //配送店铺ID
    private var mOrderSn = ""      //订单编号
    private var mShippingSn = ""   //运单编号
    private var mAdminId = ""      //配送员ID
    private var mAdminName = ""    //配送员名称
    private var mAdminPhone = ""   //配送员电话
    private var mOrderMethod = ""  //订单类型
    private var mHopeDate = ""     //预约时间
    private var mEstimateDate = "" //预计送达

    private var mReceivePhone = ""
    private var mReceiveAdress = ""
    private var mReceiveLat = ""
    private var mReceiveLng = ""

    override fun getViewModel() = get<DeliverViewModel>()

    override fun initData() {
        initTitle(title = "商品派单")

        initLayout()

        // 操作模式
        intent.getExtra("mode").also {
            mSendMode = it
            (it == "shipped").condition {
                tvTitle?.text = "商品转派"
                mBinding.btSend.text = "转派"
            }
        }

        getData()
    }

    private fun initLayout() {
        mBinding.sendList.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(getIContext())

            addItemDecoration(
                SpaceTBDecoration(
                    top = 5f,
                    hasHeader = false,
                    hasFooter = false,
                    spaceColor = R.color.white
                )
            )

            mAdapter = SlimAdapter.creator()
                .register<OrderGoods>(R.layout.item_order_detail_list) { jector, bean, _ ->
                    jector.apply {
                        text(R.id.item_order_name, bean.name)
                        text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                        text(
                            R.id.item_order_price,
                            when (mSendMode) {
                                "shipped" -> "单价：${bean.price.formatDecimal()}元"
                                else -> "单价："
                            }
                        )
                        text(R.id.item_order_num, "x${bean.quantity}")

                        visibility(
                            R.id.item_order_img_label,
                            visibleValue { bean.first }
                        )

                        with<ImageView>(R.id.item_order_img) {
                            it.loadImage(bean.thumbnail)
                        }

                        with<ImageView>(R.id.item_order_img_type) {
                            when (mOrderMethod) {
                                "offline" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order03)
                                }

                                "eleme", "elemengc" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order04)
                                }

                                "meituan" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order05)
                                }

                                "nongfu" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order06)
                                }

                                "jd" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order10)
                                }

                                "taobao" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order11)
                                }

                                "pinduoduo" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order12)
                                }

                                "dummy" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order22)
                                }

                                "ali" -> {
                                    it.visible()
                                    it.setImageResource(R.mipmap.icon_order26)
                                }

                                else -> it.gone()
                            }
                        }

                        with<ImageView>(R.id.item_order_img_status) {
                            it.isVisible = mHopeDate.isNotEmpty()

                            mHopeDate.notEmpty {
                                it.setImageResource(
                                    conditionIf(
                                        longValue < mEstimateDate.longValue,
                                        R.mipmap.icon_order07,
                                        R.mipmap.icon_order02
                                    )
                                )
                            }
                        }
                    }
                }
                .attachTo(this)
        }
    }

    override fun initListener() {
        mOrderSn = intent.getExtra("orderSn")
        mShippingSn = intent.getExtra("shippingSn")

        mBinding.apply {
            // 结算金额设置
            sendSettle.filters =
                arrayOf(
                    DecimalNumberFilter(),
                    NameLengthFilter(8)
                )

            sendCall.oneClick {
                mReceivePhone.notEmpty {
                    showBottomPhoneDialog(this)
                }
            }

            sendAdress.longClick {
                mReceiveAdress.notEmpty {
                    copyStringToClip(this)
                    showToast("地址复制成功！")
                }
            }

            sendWhereLl.oneClick {
                // 经纬度为空时，不显示距离
                startActivityEx<OrderShipWhereActivity>(
                    "lat" to mReceiveLat,
                    "lng" to mReceiveLng
                )
            }

            sendWhoLl.oneClick {
                mShopId.ifEmpty {
                    showToast("请选择配送站点")
                    return@oneClick
                }

                startActivityEx<OrderShipWhoActivity>("shopId" to mShopId)
            }

            sendNumCopy.oneClick {
                mOrderSn.notEmpty {
                    copyStringToClip(this)
                    showToast("订单编号复制成功！")
                }
            }

            btSend.oneClick {
                when {
                    mShopId.isEmpty() -> {
                        showToast("请选择配送站点")
                        return@oneClick
                    }

                    mSellerId == mShopOwnerId && mAdminId.isEmpty() -> {
                        showToast("请选择配送人员")
                        return@oneClick
                    }

                    mSellerId != mShopOwnerId
                            && sendSettleLl.isVisible
                            && serviceId in OrderService.UNION_CONTROL
                            && sendSettle.content.isEmpty() -> {
                        showToast("请输入结算金额")
                        return@oneClick
                    }
                }

                getViewModel()
                    .deliveryDph(
                        shippingSn = mShippingSn.ifEmpty { "88.${mOrderSn}" },
                        shopId = mShopId,
                        adminId = mAdminId,
                        transfer = mSellerId != mShopOwnerId,
                        price = sendSettle.content,
                        memo = sendMemo.textTrim
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            (mSendMode == "shipped")
                                .conditionElse(
                                    actionTrue = {
                                        showToast("订单转派成功！")

                                        intent
                                            .getIntExtra("index", -1)
                                            .also {
                                                (it > -1).condition {
                                                    // 更新订单列表
                                                    LiveEventBus
                                                        .get("orderList")
                                                        .post("refresh")
                                                }
                                            }

                                        // 更新订单详情
                                        LiveEventBus
                                            .get("orderDetail")
                                            .post("refresh")
                                    },
                                    actionFalse = {
                                        showToast("派单成功！")

                                        // 更新运单列表
                                        LiveEventBus
                                            .get("deliverList")
                                            .post("refresh")

                                        // 更新运单详情
                                        LiveEventBus
                                            .get("deliverDetail")
                                            .post("refresh")
                                    }
                                )

                            finishView()
                        }
                    )
            }
        }

        observe<String>("orderShip") { result ->
            val items = result.split(",")
            when (items[0]) {
                "shop" -> {
                    mShopId = items[1]
                    mShopOwnerId = items[4]
                    mAdminId = ""
                    mAdminName = ""
                    mAdminPhone = ""

                    mBinding.apply {
                        // 配送站点
                        sendWhere.text = items[2]
                        // 配送人员
                        sendWho.text = ""
                        sendWho.hint =
                            (mSellerId == mShopOwnerId)
                                .conditionElseValue(
                                    actionTrue = { "请选择配送人员" },
                                    actionFalse = { "请选择配送人员(选填)" }
                                )

                        // 结算金额输入
                        optionSettlePrice()
                    }
                }

                "admin" -> {
                    mAdminId = items[1]
                    mAdminName = items[2]
                    mAdminPhone = items[3]

                    mBinding
                        .sendWho
                        .text = mAdminName + mAdminPhone.ifNotEmpty { " - $it" }
                }
            }
        }
    }

    /**
     * 判断结算金额显隐
     */
    private fun optionSettlePrice() {
        mBinding.apply {
            sendSettleLl.isVisible =
                mSendMode == "shipped" && mSellerId != mShopOwnerId

            sendSettle.hint =
                (sendSettleLl.isVisible
                        && serviceId in OrderService.UNION_CONTROL)
                    .conditionElseValue(
                        actionTrue = { "请输入结算金额" },
                        actionFalse = { "请输入结算金额(选填)" }
                    )
        }
    }

    /**
     * 订单详情
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderInfo(mOrderSn)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = { result ->
                    val obj = JSONObject(result)

                    mShopId = obj.optNotNull("shopId")
                    mOrderSn = obj.optNotNull("sn")
                    mOrderMethod = obj.optNotNull("orderMethod")
                    mAdminId = obj.optNotNull("adminId")
                    mAdminName = obj.optNotNull("adminName")
                    mAdminPhone = obj.optNotNull("adminPhone")
                    mHopeDate = obj.optNotNull("hopeDate")
                    mSellerId = obj.optNotNull("sellerId")
                    mShopOwnerId = obj.optNotNull("shopOwnerId")

                    mBinding.apply {
                        // 美团订单金额判断
                        sendShiLl.isVisible = mOrderMethod != "meituan"
                        sendMeiLl.isVisible = mOrderMethod == "meituan"

                        sendTotal.text = obj.optNotNull("quantity")
                        sendAmount.text = obj.optNotNull("price").formatDecimal()

                        sendWhere.text = obj.optNotNull("shopName")
                        sendWho.text = mAdminName + mAdminPhone.ifNotEmpty { " - $it" }
                        sendWho.hint = (mSellerId == mShopOwnerId)
                            .conditionElseValue(
                                actionTrue = { "请选择配送人员" },
                                actionFalse = { "请选择配送人员(选填)" }
                            )

                        (mSendMode == "shipped")
                            .also {
                                sendAmountLl.isVisible = it
                                sendShiLl.isVisible = it
                            }
                            .condition {
                                // 电子水票
                                sendShui.text = "–${
                                    obj.optNotNull("exchangeDiscount")
                                        .also {
                                            sendShuiLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                                // 金币
                                sendCoin.text = "–${
                                    obj.optNotNull("pointDiscount")
                                        .also {
                                            sendCoinLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                                // 优惠券
                                sendYou.text = "–${
                                    obj.optNotNull("couponDiscount")
                                        .also {
                                            sendYouLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                                // 活动优惠
                                sendHuo.text = "–${
                                    obj.optNotNull("activityDiscount")
                                        .also {
                                            sendHuoLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                                // 单品优惠
                                sendDan.text = "–${
                                    obj.optNotNull("dragonDiscount")
                                        .also {
                                            sendDanLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                                // 会员折扣
                                sendHui.text = "–${
                                    obj.optNotNull("vipDiscount")
                                        .also {
                                            sendHuiLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                                // 客服调价
                                sendTiao.text = "–${
                                    obj.optNotNull("offsetAmount")
                                        .also {
                                            sendTiaoLl.isVisible = it.doubleValue != 0.0
                                        }.replace("-", "")
                                } 元"
                                // 空桶押金
                                sendBucket.text = "+${
                                    obj.optNotNull("pledgePayable")
                                        .also {
                                            sendBucketLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元(数量: ${obj.optNotNull("pledgeQuantity")})"
                                // 运费
                                sendFee.text = "+${
                                    obj.optNotNull("freight")
                                        .also {
                                            sendFeeLl.isVisible = it.doubleValue > 0
                                        }.formatDecimal()
                                } 元"
                            }
                        obj.optNotNull("amountPaid").also {
                            // 实付款
                            sendShi.text = it.formatDecimal()
                            // 美团实收金额
                            sendMeiShou.text = it.formatDecimal()
                        }
                        // 美团实付金额
                        sendMeiFu.text = obj.optNotNull("amountPayable").formatDecimal()

                        // 结算金额
                        sendJie.text =
                            obj.optNotNull("settlementPrice")
                                .also {
                                    (it.doubleValue > 0.0)
                                        .condition {
                                            sendSettle.setText(it.formatDecimal())
                                        }

                                    sendJieLl.isVisible =
                                        mSendMode != "shipped" && it.doubleValue > 0.0

                                    // 结算金额输入
                                    optionSettlePrice()
                                }.formatDecimal()

                        /*---------------------- 客户信息 ----------------------*/
                        val objReceive = obj.optJSONObject("receiver") ?: JSONObject()
                        mReceivePhone = objReceive.optNotNull("phone")
                        mReceiveAdress = objReceive.optNotNull("areaName")
                        mReceiveAdress += objReceive.optNotNull("address")
                        mReceiveLat = objReceive.optNotNull("lat")
                        mReceiveLng = objReceive.optNotNull("lng")
                        // 姓名电话
                        sendName.text = "${objReceive.optNotNull("consignee")}  ${
                            when {
                                userRole in "1,2"
                                        || privacyStatus == "off" -> mReceivePhone

                                else -> mReceivePhone.phoneReplaceWithStar()
                            }
                        }"
                        // 是否拨打电话
                        sendCall.isVisible = userRole in "1,2"
                        // 收货地址
                        sendAdress.text = mReceiveAdress
                        // 买家留言
                        sendMai.text =
                            obj.optNotNull("memo")
                                .notEmpty { sendMaiLl.visible() }
                        // 商家备注
                        sendCmemo.text =
                            obj.optNotNull("cardMemo")
                                .notEmpty { sendCmemoLl.visible() }

                        /*---------------------- 订单信息 ----------------------*/
                        // 订单状态
                        sendStatus.text = obj.optNotNull("statusDescr")
                        // 订单编号
                        sendNum.text = mOrderSn
                        // 订单类型
                        sendType.text =
                            obj.optNotNull("orderMethod")
                                .run {
                                    notEmpty { sendTypeLl.visible() }

                                    when (this) {
                                        "online" ->
                                            when (obj.optNotNull("paymentPluginId")) {
                                                "ticketPayPlugin" -> "货到付款"
                                                else -> "线上订单"
                                            }

                                        "ali" ->
                                            when (obj.optNotNull("paymentPluginId")) {
                                                "ticketPayPlugin" -> "货到付款"
                                                else -> "支付宝"
                                            }

                                        "offline" -> "人工报单"
                                        "history" -> "人工补单"
                                        "nongfu" -> "农夫APP"
                                        "meituan" -> "美团"
                                        "eleme", "elemengc" -> "饿了么"
                                        "jd" -> "京东"
                                        "taobao" -> "淘宝"
                                        "pinduoduo" -> "拼多多"
                                        else -> "其他"
                                    }
                                }
                        // 支付状态
                        sendMethod.text =
                            when (mOrderMethod) {
                                "offline" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    obj.optNotNull("payMethod")
                                                        .run {
                                                            isEmpty()
                                                                .conditionElseValue(
                                                                    actionTrue = {
                                                                        sendMethodLl.visible()
                                                                        "未支付"
                                                                    },
                                                                    actionFalse = { "已支付" }
                                                                )
                                                        }
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                "online", "ali" ->
                                    obj.optNotNull("payStatus")
                                        .run {
                                            when (this) {
                                                "unpaid" -> {
                                                    sendMethodLl.visible()
                                                    "未支付"
                                                }

                                                else -> "已支付"
                                            }
                                        }

                                else -> "已支付"
                            }
                        // 支付方式
                        sendPay.text =
                            obj.optNotNull("payMethodName")
                                .also {
                                    sendPayLl.isGone = it.isEmpty()
                                }
                        // 下单时间
                        sendCreate.text = obj.optNotNull("createDate").getTimeString()
                        // 预计送达
                        sendYue.text =
                            obj.optNotNull("estimateDate")
                                .also { mEstimateDate = it }
                                .notEmpty { sendYueLl.visible() }
                                .getTimeString()
                        // 派单留言
                        sendPai.text =
                            obj.optNotNull("shippingMemo")
                                .trimEnd('\n')
                                .notEmpty { sendPaiLl.visible() }
                        // 配送方式
                        sendDeliver.text =
                            obj.optNotNull("shippingMethod")
                                .notEmpty { sendDeliverLl.visible() }
                    }

                    /*---------------------- 商品信息 ----------------------*/
                    val objOrder = obj.optJSONArray("orderItems") ?: JSONArray()
                    mList.addItems(
                        JsonUtil.toList(
                            objOrder.toString(),
                            OrderGoods::class.java
                        )
                    )

                    // 是否首单
                    val isFirst = obj.optBoolean("isFirst")
                    mList.forEach { (it as OrderGoods).first = isFirst }

                    mAdapter.setDataList(mList)
                }
            )
    }

}